import {Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ViewChild} from '@angular/core';
import {TrainService} from "app/pages/train/train.service";
import {ActivatedRoute, Params, Router} from "@angular/router";
import {AuthService} from "app/shared/service/auth/auth.service";
import {CalendarBtnConfig} from "@interface/index";
import {ToolsService} from "app/shared/service/tools/tools.service";
import {SeedInfiniteScroll} from "app/shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import * as API from "@api/index";
import {TeacherService} from "app/pages/train/teacher/teacher.service";

@Component({
  selector: 'teacher-classes',
  templateUrl: './teacher-classes.component.html',
  styleUrls: ['./teacher-classes.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TeacherClassesComponent implements OnInit {
  public classes = [];
  public btnConfig: CalendarBtnConfig = new CalendarBtnConfig();
  public stateStore = {
    haveData: true,
    haveOrgIdParam: null
  };
  public dataStore = {
    testItemId: 0,
    testType: 0,
  };
  public paramStore = {
    beginDate: '',
    endDate: '',
    page: 1,
    rows: 10,
    orgUserId: '',
    testContentId: 0
  };

  @ViewChild(SeedInfiniteScroll) infiniteScroll;

  constructor(private  teacherService: TeacherService,
              private router: Router,
              private route: ActivatedRoute,
              private tools: ToolsService,
              private _authService: AuthService) {
    this.setCanlenderBtn();
    this.route.params
      .switchMap((params: Params) => {
        return this.route.queryParams;
      }).subscribe((queryParams: Params) => {
      this.dataStore.testItemId = queryParams['testItemId'];
      this.paramStore.testContentId = queryParams['testContentId'];
      if (queryParams['authOrgId']) { // 查询成绩流程
        this._authService.setAuthOrgId(queryParams['authOrgId']);
        this.stateStore.haveOrgIdParam = queryParams['authOrgId'];
      } else {
        this.dataStore.testType = queryParams['testType'];
        this.paramStore.orgUserId = this._authService.getAuthOrgId();
      }
    });
  }

  setCanlenderBtn() {
    const btnConfig = this.btnConfig;
    btnConfig.week = true;
    btnConfig.month = true;
    btnConfig.year = true;
  }

  getClassListForIdentityType() {
    if (this.stateStore.haveOrgIdParam) {
      this.getClassListForTeacher();
    } else {
      this.getClassListByTestProjectForTeacher();
    }
  }


  /**
   * 获取时间之后去请求
   * @param val
   */
  getCalendarTime(val) {
    let beginTime;
    let endTime;
    this.classes = [];
    const params = this.paramStore;
    params.page = 1;
    this.infiniteScroll.enable(true);

    beginTime = this.tools.dateTostr(val[0]);
    endTime = val[1] ? this.tools.dateTostr(val[1]) : beginTime;

    params.beginDate = beginTime;
    params.endDate = endTime;

    // 有 orgId 参数则走成绩查询流程，否则为成绩录入流程

    if (this.stateStore.haveOrgIdParam) {
      this.getClassListForTeacher();  // 成绩查询
    } else {
      this.getClassListByTestProjectForTeacher(); // 成绩录入
    }
  }


  /**
   * @description 根据测试选项獲取教练班级（录入成绩流程）
   * @author ouyqx-691
   * @date 2018-4-13
   */
  getClassListByTestProjectForTeacher(): void {
    const {beginDate, endDate, page, rows, testContentId, orgUserId} = this.paramStore;
    const params = {
      beginDate: beginDate,
      endDate: endDate,
      page: page,
      rows: rows,
      orgUserId: orgUserId,
      testItemId: testContentId
    };
    this.teacherService.getClassListByTestProjectForTeacher(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        const classes = res.data.list;
        this.paramStore.page++;
        this.infiniteScroll.complete();
        this.classes = [...this.classes, ...classes];
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        if (classes.length === 0) {
          return this.stateStore.haveData = false;
        } else {
          return this.stateStore.haveData = true;
        }
      } else {
        return this.stateStore.haveData = false;
      }
    });
  }

  /**
   * @description 班级列表（查询成绩流程）
   * @author ouyqx-691
   * @date 2017-12-30
   */
  getClassListForTeacher(): void {
    const {beginDate, endDate, page, rows, orgUserId} = this.paramStore;
    const params = {
      beginTime: beginDate,
      endTime: endDate,
      page: page,
      rows: rows,
      orgUserId: this._authService.getAuthOrgId()
    };
    this.teacherService.getClassListForTeacher(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        const classes = res.data.list;
        this.paramStore.page++;
        this.infiniteScroll.complete();
        this.classes = [...this.classes, ...classes];
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
        if (classes.length === 0) {
          return this.stateStore.haveData = false;
        } else {
          return this.stateStore.haveData = true;
        }
      } else {
        return this.stateStore.haveData = false;
      }
    });
  }


  goToTarget(classItem) {
    console.log(classItem);
    let queryParams;
    if (this.stateStore.haveOrgIdParam) {
      const {beginDate, endDate} = this.paramStore;
      queryParams = {
        classId: classItem.classScheduleId,
        teacherId: classItem.teacherId,
        beginTime: beginDate,
        endTime: endDate,
        process: 'score-query'
      };
    } else {
      queryParams = {
        testItemId: this.dataStore.testItemId,
        testContentId: this.paramStore.testContentId,
        testType: this.dataStore.testType,
        classId: classItem.classId,
        process: 'score-input'
      };
    }
    this.router.navigate([`/train/teacher/students`], {
      queryParams
    });
  }

  ngOnInit() {

  }

}
